<?php
	//栏目类

	class cate
	{
		var $database = null;

		function cate()
		{
			$this->database = load( 'database' );
		}

		//返回栏目列表数据
		function all( $data )
		{
			$size = isset( $data['size'] ) && preg_match( '!^\d+$!', $data['size'] ) ? $data['size'] : 12;
			$page = isset( $data['page'] ) && preg_match( '!^\d+$!', $data['page'] ) ? $data['page'] : 1;
			$order = isset( $data['order'] ) ? $data['order'] : 'id asc';
			$module_type_id = isset( $data['module_type_id'] ) ? $data['module_type_id'] : '';
			$parent_id = isset( $data['parent_cate_id'] ) ? $data['parent_cate_id'] : 0;
			$where = ' where 1=1 ';
			if ( $parent_id != 0 )
			{
				$where .= ' and parent_id=' . $parent_id;
			}
			if ( $module_type_id != '' )
			{
				$where .= ' and module_type_id=' . $module_type_id;
			}
			$count = 'from cate' . $where;
			$list = 'select * ' . $count .  ' order by ' . $order;
			$result = $this->database->split( $count, $list, $size, $page );

			return $result;
		}

		//获取具体id的栏目数据
		function get( $data )
		{
			$result = array();
			if ( isset( $data['id'] ) && preg_match( '!^\d+$!', $data['id'] ) ) $result = $this->database->unique( 'select * from cate where status=0 and id = ' . $data['id'] );
			return $result;
		}

		//修改具体栏目的数据
		function set( $data )
		{
			$result = array( 'success' => false, 'message' => array() );
			$validation = load( 'validation' );
			$field = array();

			$field['cname']['kind'] = '';
			$field['cname']['type'] = 'text';
			$field['cname']['min'] = '1';
			$field['cname']['max'] = '32';
			$field['cname']['info'] = '请输入栏目名称';

			$field['ename']['kind'] = '';
			$field['ename']['type'] = 'text';
			$field['ename']['min'] = '1';
			$field['ename']['max'] = '255';
			$field['ename']['info'] = '请输入栏目英文名称';

			$field['module_type_id']['kind'] = '';
			$field['module_type_id']['type'] = 'num';
			$field['module_type_id']['min'] = '1';
			$field['module_type_id']['max'] = '11';
			$field['module_type_id']['info'] = '请选择内容模型';

			$field['parent_id']['kind'] = '';
			$field['parent_id']['type'] = 'num';
			$field['parent_id']['min'] = '1';
			$field['parent_id']['max'] = '11';
			$field['parent_id']['info'] = '请选择父栏目';

			$check = $validation->validate( $field, $data );

			if ( count( $check ) == 0 )
			{
				if ( $data['ename'] == 'widget' )
				{
					$result['success'] = false;
					$result['message'][] ='名称限制' . $data['ename'];
					return $result;
				}

				//取得修改前的栏目信息
				$cateinfo = $this->get( $data );

				//取得修改前的栏目结构
				$dirinfo = $this->getdir( $data['id'] );
				$source = config( 'dir.www' ).$dirinfo['dir'];//无二级域名

				//修改文件夹名称用
				$target = dirname ( $source ) . '/' . $data['ename'];

				//栏目的栏目结构有修改
				//if ( ( $data['parent_id'] != $cateinfo['parent_id'] ) || ( $data['dev_domain'] !='' && $cateinfo['dev_domain'] =='' ) || ( $data['dev_domain'] =='' && $cateinfo['dev_domain'] !='') )
				if ( ( $data['parent_id'] != $cateinfo['parent_id'] ) )
				{
					//取得修改后的栏目结构

					$dirinfo1 = $this->getdir( $data['parent_id'] );
					$target = config( 'dir.www' ).$dirinfo1['dir'] ;//无二级域名

					$move_result = $this->move_dir( $source,$target );
					if ( $move_result['success'] != 1 )
					{
						return $move_result;
					}
					$deldir = $this->deldir( $source );
					if ( $deldir['success'] != 1 )
					{
						return $deldir;
					}

					//修改文件夹名称用
					$source = $target . $cateinfo['ename'];
					$target = $target . $data['ename'];
				}

				//栏目不存在(在数据库中有记录,但没有实际的路径),创建目录
				if ( ! is_dir( $source ) )
				{
					mkdir($source, 0755, true );
				}

				//栏目英文名有改变
				if ( $data['ename'] != $cateinfo['ename'] )
				{
					$rname = rename( $source, $target );
					if ( !$rname )
					{
						$result['success'] = false;
						$result['message'][] ='重命名文件夹出错';
						return $result;
					}
				}

				//修改数据库
				$this->database->start();
				$this->database->set( 'cate', $data, array( 'id' => $data['id'] ) );

				if ( $this->database->end() )
				{
					$result['success'] = true;
				}
				else
				{
					$result['message'][] = '执行修改失败';
				}
			}
			else
			{
				$result['message'][] = $check;
			}

			return $result;
		}

		//添加新的栏目内容
		function add( $data )
		{
			$result = array( 'success' => false, 'message' => array() );
			$validation = load( 'validation' );
			$field = array();

			$field['cname']['kind'] = '';
			$field['cname']['type'] = 'text';
			$field['cname']['min'] = '1';
			$field['cname']['max'] = '32';
			$field['cname']['info'] = '请输入栏目名称';

			$field['ename']['kind'] = '';
			$field['ename']['type'] = 'text';
			$field['ename']['min'] = '1';
			$field['ename']['max'] = '255';
			$field['ename']['info'] = '请输入栏目英文名称';

			$field['module_type_id']['kind'] = '';
			$field['module_type_id']['type'] = 'num';
			$field['module_type_id']['min'] = '1';
			$field['module_type_id']['max'] = '11';
			$field['module_type_id']['info'] = '请选择内容模型';

			$field['parent_id']['kind'] = '';
			$field['parent_id']['type'] = 'num';
			$field['parent_id']['min'] = '1';
			$field['parent_id']['max'] = '11';
			$field['parent_id']['info'] = '请选择父栏目';

			$check = $validation->validate( $field, $data );

			if ( count( $check ) == 0 )
			{
				if ( $data['ename'] == 'widget' )
				{
					$result['success'] = false;
					$result['message'][] ='名称限制' . $data['ename'];
					return $result;
				}

				$this->database->start();
				$id = $this->database->add( 'cate', $data );

				if ( preg_match( '!^\d+$!', $id ) && $this->database->end() )
				{
					$dirinfo = $this->getdir( $id );
					$dir = config( 'dir.www' ).$dirinfo['dir'];//无二级域名

					if ( mkdir($dir, 0755, true ) )
					{
						$result['success'] = true;
					}
					else
					{
						$result['message'][] = '创建栏目失败'.$dir;
					}
				}
				else
				{
					$result['message'][] = '添加栏目失败';
				}
			}
			else
			{
				$result['message'][] = $check;
			}

			return $result;
		}

		//删除具体栏目
		function del( $data )
		{
			$return = array( 'success'=>false,'message'=>array() );
			if ( isset( $data['id'] ) && preg_match( '!^\d+$!', $data['id'] ) )
			{
				//$re = 1;
				$dirinfo = $this->getdir( $data['id'] );
				$dir1 = config( 'dir.www' );//无二级域名
				$dir = $dir1.$dirinfo['dir'];

				if ( ! is_dir( $dir ) )
				{
					$data = $this->database->unique( 'select id from cate where id = ' . $data['id'] );
					if ( ! empty( $data ) )
					{
						$this->database->command( 'delete from cate where id = ' . $data['id'] );
					}

					$return['success'] =  true;
					return $return;
				}
				$handle = opendir($dir);
				while ( $file=readdir( $handle ) )
				{
					if ($file != "." && $file != ".." && $file!='' )
					{
						$return['message'][] = '栏目不为空,请先删除栏目下的文件或栏目';
						return $return;
					 }
				}
				closedir( $handle );
				if( rmdir( $dir ) )
				{
					$return['success'] = $this->database->command( 'delete from cate where id = ' . $data['id'] );
				}
			}
			return $return;
		}

		/**
		 * 查看栏目是否有子栏目
		 * @param array arr   栏目数组
		 * @param integer pid 栏目id
		 * @return bloon false or true
		 */
		function existsChild( $arr, $pid )
		{
			 foreach ( $arr as $val )
			 {
				  if( $val['parent_id'] == $pid )
				  {
					 return true;
				  }
			 }
			 return false;
		}

		/**
		 * 查看栏目2是否是栏目1的下级栏目
		 * @param integer id1 栏目id
		 * @param integer id2 栏目id
		 * @return bloon false or true
		 */
		function isChild( $id1, $id2 )
		{
			 if ( $id2 ==0 )
			 {
				return false;
			 }
			 $sql = "select parent_id from cate where id=" . $id2;
			 $data = $this->database->unique( $sql );
			 if ( $data['parent_id'] == $id1 )
			 {
				return true;
			 }
			 if ( $data['parent_id'] !=0 )
			 {
				$this->isChild( $id1, $data['parent_id'] );
			 }
			 return false;
		}

		/**
		 * 获得以树形结构顺序的栏目数组
		 * @param array arr   栏目数组
		 * @param integer pid 栏目父id
		 * @param integer level 栏目级别
		 * @return array( 0=>array('id'=>'', 'cname'=>'',......) ) 栏目信息
		 */
		function getcatelist( $arr, $pid = 0, $level = 0 )
		{
			 $array = array();

			 foreach ($arr as $key => $val)
			 {
				  if($val['parent_id'] == $pid)
				  {
					   $arrChild = array();
					   if($pid != 0)
					   {
							$level++;
					   }
					   $arr[$key]['level'] = $level;
					   $array[] = $arr[$key];
					   if($this->existsChild($arr, $val['id']))
					   {
							$arrChild = $this->getcatelist($arr, $val['id'], $level);
					   }
					   $array = array_merge($array, $arrChild);
					   if($pid != 0)
					   {
							$level--;
					   }
				  }
			 }
			 return $array;
		}

		/**
		 * 获得以树形结构顺序的栏目数组,因为要递归调用getcatelist( $arr ),要从外部传递参数$arr，
		 *所以页面中不能直接调用getcatelist( $arr )来获得树形栏目数组
		 * @return array( 0=>array('id'=>'', 'cname'=>'',......) ) 树形结构栏目信息
		 */
		function getcatealllist ( $parent_cateid = 0, $include_parent_self = false )
		{
			$return = array();

			$arr = $this->database->select( 'select * from cate' );
			$return = $this->getcatelist( $arr, $parent_cateid );
			if ( $include_parent_self == true )
			{
				foreach ( $arr as $index => $value )
				{
					if ( $value['id'] == $parent_cateid )
					{
						$return[] = $value;
					}
				}
			}

			return $return;
		}


		/**
		 * 获得栏目的栏目地址
		 * @param integer id 栏目id
		 * @return array ('dir'=>栏目信息，'second_domain'=>等级栏目是否绑定二级域名 0 否 1 是)
		 */
		function getdir( $id )
		{
			 $dirinfo = array ( 'dir' => '', 'second_domain' => 0 );

			 if ( $id < 0 )
			 {
				return $dirinfo;
			 }
			 $sql = "select ename,parent_id,dev_domain from cate where id=" . $id;
			 $data = $this->database->unique( $sql );

			 if( $data['parent_id'] !=0 )
			 {
				$dirinfo = $this->getdir( $data['parent_id'] );
			 }
			 else
			{
				 if( $data['dev_domain'] != '' )
				{
					 $dirinfo['second_domain'] = 1;
				}
			}
			$dirinfo['dir'] .= $data['ename'] . '/' ;

			 return $dirinfo;
		}

		//删除栏目及栏目下的文件
		function deldir( $dir )
		{
			$return = array( 'success'=>false,'message'=>array() );
			if ( is_dir( $dir ) )
			{
				$dh=opendir( $dir );
				while ( $file=readdir( $dh ) )
				{
					if( $file!="." && $file!=".." )
					{
						$fullpath=$dir."/".$file;
						if( !is_dir( $fullpath ) )
						{
							unlink( $fullpath );
						}
						else
						{
							$this->deldir( $fullpath );
						}
					}
				}
				closedir( $dh );
				if( rmdir( $dir ) )
				{
					$return['success'] = true;
				}
				else
				{
					$return['message'][] = '删除栏目失败';
				}
			}
			else
			{
				$return['message'][] = '该栏目不存在';
			}
			return $return;
		}

		/**
		 * 移动栏目
		 * @param string source 源栏目
		 *@param string target 目标栏目
		 * @return array ('success'=>false，'message'=>'出错信息')
		 */
		function move_dir( $source,$target )
		{
			$return = array ('success'=>false, 'message'=>'');
			$entry = '';
			$dest_name = '';
			if( is_dir( $source ) )
			{
				$dest_name=basename($source);
				$creat_dir=$target."/".$dest_name;

				if( !mkdir( $creat_dir,0755,true ) )
				{
					$return['success']=false;
					$return['message'][]='创建栏目失败';
					return $return;
				}

				$d=dir( $source );
				while( ( $entry=$d->read() )!==false )
				{
					if(is_dir($source."/".$entry))
					{
						if($entry=="."|| $entry=="..")
						{
							continue;
						}
						else
						{
							$se=$source."/".$entry;
							$td=$target."/".$dest_name;
							$this->move_dir($se,$td);
						}
					}
					else
					{
						$se=$source."/".$entry;
						$td=$target."/".$dest_name."/".$entry;
						if( !copy( $se,$td ) )
						{
							$return['success']=false;
							$return['message'][]='copy栏目失败';
							return $return;
						}
					}
				}
			}
			else
			{
				$se=$source."/".$entry;
				$td=$target."/".$dest_name;
				if( !copy( $se,$td ) )
				{
					$return['success']=false;
					$return['message'][]='copy栏目失败';
					return $return;
				}
			}
			$return['success']=true;
			 return $return;
		}

		/**
		 * 对多维数组映射成多维field1=>field2数组
		 * detail description
		 * @param string user
		 * @param integer id
		 * @return int|string|array|object|mixed
		 */
		function x_to_y( $data, $filedx, $fieldy )
		{
			$tmp = array( '整站通用栏目' );
			if ( is_array( $data ) )
			{
				foreach ( $data as $index => $value )
				{
					$tmp[$value[$filedx]] = $value[$fieldy];
				}
			}

			return $tmp;
		}
}
?>